package com.cnb.telepathytalk.adapter;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;
import java.util.TreeMap;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.cnb.telepathytalk.ProfileViewActivity;
import com.cnb.telepathytalk.R;
import com.cnb.telepathytalk.TelepathyTalkApplication;
import com.cnb.telepathytalk.dto.MsgDTO;
import com.cnb.telepathytalk.util.LazyImageLoader;
import com.emilsjolander.components.stickylistheaders.StickyListHeadersAdapter;

public class MsgListAdapter extends BaseAdapter implements StickyListHeadersAdapter {
	private Context context;
	private HashMap<String, String> peopleNameMap;
	private HashMap<String, String> peoplePictureMap;
	private ArrayList<MsgDTO> list;
	private LayoutInflater inflater;
	private int layoutResMe;
	private int layoutResOther;
	private LazyImageLoader imageLoader;
	private TreeMap<String, Integer> sections;

	public MsgListAdapter(Context context) {
		super();
		this.context = context;
		this.peopleNameMap = new HashMap<String, String>();
		this.peoplePictureMap = new HashMap<String, String>();
		this.list = new ArrayList<MsgDTO>();
		this.inflater = LayoutInflater.from(context);
		this.layoutResMe = R.layout.list_item_msg_me;
		this.layoutResOther = R.layout.list_item_msg_other;
		this.imageLoader = new LazyImageLoader(context, R.drawable.profile_talk, 50, LazyImageLoader.SET_IMAGE);
		this.sections = new TreeMap<String, Integer>();
	}

	public HashMap<String, String> getPeopleNameMap() {
		return peopleNameMap;
	}

	public HashMap<String, String> getPeoplePictureMap() {
		return peoplePictureMap;
	}

	public MsgDTO getIndexItem(int index) {
		for (MsgDTO i : list) {
			if (i.getMsgIndex() == index) {
				return i;
			}
		}
		return null;
	}

	public void clear() {
		list.clear();
	}

	@Override
	public int getCount() {
		return list.size();
	}

	public ArrayList<MsgDTO> getList() {
		return list;
	}

	public void addItem(MsgDTO item) {

		String key = item.getSendTime().substring(0, 8);
		if (!sections.containsKey(key))
			sections.put(key, list.size());

		list.add(item);
	}

	@Override
	public MsgDTO getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	/** 자소채팅 뷰 추가 및 수정 */
	public void setTempItem(MsgDTO temp) {
		MsgDTO item = null;
		for (int i = 0; i < getCount(); i++) {
			item = getItem(i);
			if (item.getSendUcode() == temp.getSendUcode() && item.getMsgIndex() == 0) {
				item.setMsg(temp.getMsg());
				return;
			}
		}
		list.add(temp);
	}

	/** 자소채팅 뷰 삭제 */
	public void removeTempItem(int deleteUcode) {
		MsgDTO item = null;
		for (int i = 0; i < getCount(); i++) {
			item = getItem(i);
			if (item.getSendUcode() == deleteUcode && item.getMsgIndex() == 0) {
				list.remove(item);
				break;
			}
		}
	}

	/** 레이아웃 생성 */
	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		MsgDTO item = list.get(position);
		Holder holder = null;

		if (item.getChatState() == MsgDTO.STATE_INPUT || item.getChatState() == MsgDTO.STATE_OUTPUT) {
			convertView = inflater.inflate(R.layout.section_chating_room, null);
			((TextView) convertView.findViewById(R.id.textView1)).setText(item.getMsg());
			return convertView;
		}

		if (item.getSendUcode() == TelepathyTalkApplication.uCode) {
			convertView = inflater.inflate(layoutResMe, null);
			holder = new Holder(convertView);
		} else {
			convertView = inflater.inflate(layoutResOther, null);
			holder = new Holder(convertView);

			imageLoader.DisplayImage(peoplePictureMap.get("" + item.getSendUcode()), holder.getProfile());
			holder.getProfile().setOnClickListener(new ProfileClickListener(item));
			try {
				holder.getName().setText(peopleNameMap.get("" + item.getSendUcode()));
			} catch (Exception e) {
				holder.getName().setText(R.string.chat_unknown);
			}
		}

		switch (item.getChatState()) {
		case MsgDTO.STATE_IMAGE:
			holder.getMsg().setCompoundDrawablesWithIntrinsicBounds(R.drawable.file_photo, 0, 0, 0);
			holder.getMsg().setOnClickListener(new MediaClickListener(item));
			break;

		case MsgDTO.STATE_VIDEO:
			holder.getMsg().setCompoundDrawablesWithIntrinsicBounds(R.drawable.file_video, 0, 0, 0);
			holder.getMsg().setOnClickListener(new MediaClickListener(item));
			break;

		default:
			holder.getMsg().setText(item.getMsg());
			break;
		}

		if (item.getChatState() != MsgDTO.STATE_PROGRESS) {
			holder.getInfoView().setVisibility(View.VISIBLE);
			holder.getTime().setText(getDate(item.getSendTime()));

			if (item.getNonReadUser() != 0) {
				holder.getNonRead().setText("" + item.getNonReadUser());
			}
		} else {
			holder.getInfoView().setVisibility(View.GONE);
		}
		return convertView;
	}

	/** 오전 오후 시 분 생성 */
	private String getDate(String time) {
		try {
			Calendar createDay = Calendar.getInstance();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
			createDay.setTime(sdf.parse(time));

			String am_pm = createDay.get(Calendar.AM_PM) == Calendar.PM ? context.getString(R.string.chat_pm) : context.getString(R.string.chat_am);
			int hour = createDay.get(Calendar.HOUR);
			int minute = createDay.get(Calendar.MINUTE);
			return String.format(Locale.getDefault(), "%s %02d : %02d", am_pm, hour, minute);
		} catch (ParseException e) {
		}
		return time;
	}

	/** 사진, 동영상 클릭 이벤트 리스너 */
	private class MediaClickListener implements View.OnClickListener {
		private static final String DEFAUL_ADDRESS = "http://server.telepathytalk.com/dataUpload.php?filename=";
		private MsgDTO item;

		public MediaClickListener(MsgDTO item) {
			super();
			this.item = item;
		}

		@Override
		public void onClick(View v) {
			String[] arr = item.getMsg().split(",");
			String address = DEFAUL_ADDRESS + arr[arr.length - 1].trim();
			Log.i("qweqw", address);

			switch (item.getChatState()) {
			case MsgDTO.STATE_IMAGE:
				Intent intent1 = new Intent();
				intent1.setAction(Intent.ACTION_VIEW);
				Uri uri1 = Uri.parse(address);
				intent1.setDataAndType(uri1, "image/*");
				context.startActivity(intent1);
				break;

			case MsgDTO.STATE_VIDEO:
				Intent intent2 = new Intent();
				intent2.setAction(Intent.ACTION_VIEW);
				Uri uri2 = Uri.parse(address);
				intent2.setDataAndType(uri2, "video/*");
				context.startActivity(intent2);
				break;
			}
		}
	}

	/** 프로필 사진 클릭 이벤트 리스너 */
	private class ProfileClickListener implements View.OnClickListener {
		private MsgDTO item;

		public ProfileClickListener(MsgDTO item) {
			super();
			this.item = item;
		}

		@Override
		public void onClick(View v) {
			Intent intent = new Intent(context, ProfileViewActivity.class);
			intent.putExtra(ProfileViewActivity.TAG_INTEGER, item.getSendUcode());
			context.startActivity(intent);
		}
	}

	/** 레이아웃 홀더 */
	private class Holder {
		private View baseView;

		private ImageView profile;
		private TextView name;
		private TextView msg;
		private TextView time;
		private TextView nonRead;
		private View msglayout;

		public Holder(View view) {
			super();
			baseView = view;
		}

		public ImageView getProfile() {
			if (profile == null)
				profile = (ImageView) baseView.findViewById(R.id.profile);
			return profile;
		}

		public TextView getName() {
			if (name == null)
				name = (TextView) baseView.findViewById(R.id.name);
			return name;
		}

		public TextView getMsg() {
			if (msg == null)
				msg = (TextView) baseView.findViewById(R.id.msg);
			return msg;
		}

		public TextView getTime() {
			if (time == null)
				time = (TextView) baseView.findViewById(R.id.time);
			return time;
		}

		public TextView getNonRead() {
			if (nonRead == null)
				nonRead = (TextView) baseView.findViewById(R.id.nonRead);
			return nonRead;
		}

		public View getInfoView() {
			if (msglayout == null)
				msglayout = baseView.findViewById(R.id.msgLayout);
			return msglayout;
		}
	}

	/************************************
	 * 섹션
	 */

	/** 섹션 구분 값 */
	@Override
	public long getHeaderId(int arg0) {
		return Long.parseLong(list.get(arg0).getSendTime().substring(0, 8));
	}

	/** 섹션 레이아웃 뷰 */
	@Override
	public View getHeaderView(int arg0, View arg1, ViewGroup arg2) {
		View view = inflater.inflate(R.layout.section_chating_room, null);
		((TextView) view.findViewById(R.id.textView1)).setText(getDate2(list.get(arg0).getSendTime()));
		return view;
	}

	/** 년 월 일 요일 생성 */
	private String getDate2(String time) {
		try {
			Calendar createDay = Calendar.getInstance();

			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss", Locale.getDefault());
			createDay.setTime(sdf.parse(time));

			int year = createDay.get(Calendar.YEAR);
			int month = createDay.get(Calendar.MONTH) + 1;
			int day = createDay.get(Calendar.DAY_OF_MONTH);
			int dayOfWeek = createDay.get(Calendar.DAY_OF_WEEK);

			StringBuffer date = new StringBuffer("");
			date.append(year).append(context.getString(R.string.chat_year)).append(" ");
			date.append(month).append(context.getString(R.string.chat_month)).append(" ");
			date.append(day).append(context.getString(R.string.chat_day)).append(" ");

			switch (dayOfWeek) {
			case Calendar.MONDAY:
				date.append(context.getString(R.string.chat_day_of_week1));
				break;
			case Calendar.TUESDAY:
				date.append(context.getString(R.string.chat_day_of_week2));
				break;
			case Calendar.WEDNESDAY:
				date.append(context.getString(R.string.chat_day_of_week3));
				break;
			case Calendar.THURSDAY:
				date.append(context.getString(R.string.chat_day_of_week4));
				break;
			case Calendar.FRIDAY:
				date.append(context.getString(R.string.chat_day_of_week5));
				break;
			case Calendar.SATURDAY:
				date.append(context.getString(R.string.chat_day_of_week6));
				break;
			case Calendar.SUNDAY:
				date.append(context.getString(R.string.chat_day_of_week7));
				break;
			}

			return date.toString();

		} catch (ParseException e) {
		}
		return time;
	}
}